import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import productidentification.IProductIdentifier;

public class GoogleProductIdentifier implements IProductIdentifier
{
  private static final String URL_STRING = "https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyCWEJFlxufiRk2CHiiMLKZb4uH1kln7cBY&country=US&alt=atom&q=";

  // this method is strictly for testing purposes.
  public static void main(String[] args)
  {
    try
    {
      String barcode = "895035002019";

      GoogleProductIdentifier identifier = new GoogleProductIdentifier();
      String result = identifier.identifyProduct(barcode);
      System.out.println("Identifying product \"" + barcode + "\" yielded: '" + result + "'");
    }
    catch (Exception e)
    {
      System.err.print("Identifying product failed! Error: ");
      if (e.getMessage() != null)
        System.err.println(e.getMessage());
      e.printStackTrace();
    }
  }

  @Override
  public String identifyProduct(String barcode) throws Exception
  {
    URL url = getURL(barcode);
    HttpURLConnection connection = getConnection(url);

    InputStream xml = connection.getInputStream();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(xml);

    Node titleNode = doc.getElementsByTagName("s:title").item(0);
    if (titleNode != null)
      return titleNode.getTextContent();
    else
      return null;
  }

  private HttpURLConnection getConnection(URL url) throws IOException
  {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");

    return connection;
  }

  private URL getURL(String barcode) throws MalformedURLException
  {
    return new URL(URL_STRING + barcode);
  }

  @Override
  public String getName()
  {
    return "Google Product Identifier Plugin";
  }

  @Override
  public String getDescription()
  {
    return "Uses the Google APIs to identify a product given its UPC barcode.";
  }
}
